<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test5</title>
</head>
<body>
<form name="form" method="post" action="">
    <textarea name="oldString" cols="40" rows="4"></textarea>
    <br>
    转换后字符串：<br>
    <textarea name="newString" cols="40" rows="4"></textarea>
    <input name="Button" type="button" class="btn_grey" value="去掉字符串的首尾空格" onclick="trim()">
</form>

<script>
    function trim() {
        var oldString=form.oldString.value;
        if(oldString==""){
            alert("请输入字符串");
            return
        }else {
            var i=0;
            var j=oldString.length;
            for(;i<oldString.length;i++){
                if(oldString.charAt(i)!=" "){
                    break;
                }
            }

            for(;j>0;j--){
                if(oldString.charAt(j-1)!=" "){
                    break;
                }
            }

            form.newString.value=oldString.substring(i,j);
        }
    }
</script>
</body>
</html>